<template>
  <div class="info-page">
    <cp-nav-bar title="商户信息上传" />
    <van-form autocomplete="off" @submit="onSubmit" ref="form" class="infoForm">
      <van-field name="merchantName" label="商户名称" v-model="queryparams.merchantName" placeholder="请输入商户名称"
        :rules="merchantNameRules" required></van-field>
      <van-field name="merchantContacts" label="商户联系人" v-model="queryparams.merchantContacts" placeholder="请输入商户联系人"
        required :rules="nameRules"></van-field>
      <van-field name="phone" label="手机号" v-model="queryparams.phone" :rules="telephoneRules" placeholder="请输入手机号"
        required type="tel"></van-field>
      <van-field name="businessCity" v-model="queryparams.businessCity" is-link readonly label="所属区域"
        placeholder="请选择区域" required :rules="districtRules" @click="showPicker = true" />
      <van-field name="businessAddress" label="经营地址" v-model="queryparams.businessAddress" placeholder="请输入经营地址"
        :rules="addressRules" required></van-field>
      <van-field name="businessLicenseList" label="营业执照" required :rules="businessLicenseRules">
        <template #input>
          <cp-upload ref="cpUploadRef1" v-model="queryparams.businessLicenseList" type="business_license"
            @delete-success="onDeleteSuccess1"></cp-upload>
        </template>
      </van-field>
      <van-field name="corporateIdCard" label="法人身份证" required :rules="idCardimgRules">
        <template #input>
          <cp-upload ref="cpUploadRef2" v-model="queryparams.corporateIdCard" type="corporate_id_card"
            @delete-success="onDeleteSuccess2"></cp-upload>
        </template>
      </van-field>
      <div class="cp-cell1">
        <van-button native-type="submit" block round type="primary" color="#CB161D">
          提交
        </van-button>
      </div>
    </van-form>
    <van-popup v-model:show="showPicker" position="bottom">
      <van-area title="省市区" :area-list="areaList" @confirm="onConfirm" @cancel="showPicker = false" />
    </van-popup>
  </div>
</template>
<script setup lang="ts">
import { addmerchant, getmerchant } from "@/services/home";
import { onMounted, ref, reactive } from "vue";
import { showSuccessToast } from "vant";
import { useRouter } from "vue-router";
import { baseURL } from '@/utils/request'

const router = useRouter()
import { areaList } from '@vant/area-data';
import { telephoneRules, merchantNameRules, nameRules, addressRules, districtRules, businessLicenseRules, idCardimgRules } from "@/utils/rules";

const mobile = ref('185****0225')
const queryparams = ref({
  merchantName: '',
  merchantContacts: '',
  phone: '',
  businessCityCode: '',
  businessCity: '',
  businessAddress: '',
  businessLicenseList: [],
  corporateIdCard: [],
})
const cpUploadRef1 = ref()
const cpUploadRef2 = ref()

const showPicker = ref(false);

const onConfirm = (e: any) => {
  console.log('选择的内容：', e);

  showPicker.value = false;
  queryparams.value.businessCity = e.selectedOptions.map((item: any) => item.text).join('/');
  queryparams.value.businessCityCode = e.selectedValues.join(',')
};
const onSubmit = async () => {
  console.log('点击提交', queryparams.value);
  // queryparams.value.businessLicenseList = queryparams.value.businessLicenseList.map((item: any) => {
  //   console.log('item1:', item);
  //   const image1 = ref()
  //   image1.value = item.url?.split('/').slice(-1)[0] || item.split('/').slice(-1)[0]
  //   const domainRegex = /^https?:\/\/([^\/]+)\//;
  //   item = typeof (item) == 'string' ? item.replace(domainRegex, '') : '/' + item.url.replace(domainRegex, '')
  //   return {
  //     "fileName": image1.value,
  //     "filePath": item,
  //     "fileType": "business_license"
  //   }
  // })

  // queryparams.value.corporateIdCard = queryparams.value.corporateIdCard.map((item: any) => {
  //   console.log('item2:', item);

  //   const image2 = ref()
  //   image2.value = item.url?.split('/').slice(-1)[0] || item.split('/').slice(-1)[0]
  //   const domainRegex = /^https?:\/\/([^\/]+)\//;
  //   item = typeof (item) == 'string' ? item.replace(domainRegex, '') : '/' + item.url.replace(domainRegex, '')
  //   return {
  //     "fileName": image2.value,
  //     "filePath": item.url || item,
  //     "fileType": "corporate_id_card"
  //   }
  // })

  console.log('点击提交-转换后的：', queryparams.value);

  addmerchant(queryparams.value).then(res => {
    if (res.code === 200) {
      console.log('添加商家信息成功', res);
      showSuccessToast("添加成功");
      router.back()
    }
  }).catch(err => {
    console.log('添加商家信息失败', err);
  })
};

// BUSINESS_LICENSE("business_license", "营业执照"),
// CORPORATE_ID_CARD("corporate_id_card", "法人身份证"),
const onUploadSuccess1 = (image: any) => {
  console.log('onUploadSuccess1:', image);
  console.log('queryparams.value.businessLicenseList::', queryparams.value.businessLicenseList);
  queryparams.value.businessLicenseList.push(image)
  // queryparams.value.businessLicenseList.push({
  //   fileName: image.split('/').slice(-1)[0], //附件名称
  //   filePath: image, //附件访问路径
  //   fileType: 'business_license', //附件类型
  // })
  console.log('onUploadSuccess1:', queryparams.value.businessLicenseList);
}
const onDeleteSuccess1 = (item: any) => {
  console.log('删除图片', item);
  queryparams.value.businessLicenseList = queryparams.value.businessLicenseList?.filter(
    (pic: any) => {
      return pic.url !== item.url && pic !== item.url
    }
  )
}
const onUploadSuccess2 = (image: any) => {
  console.log('image', image);
  queryparams.value.corporateIdCard.push(image)
  // queryparams.value.corporateIdCard.push({
  //   fileName: image.split('/').slice(-1)[0], //附件名称
  //   filePath: image, //附件访问路径
  //   fileType: 'corporate_id_card', //附件类型
  //   })
}
const onDeleteSuccess2 = (item: any) => {
  console.log('删除图片', item);
  queryparams.value.corporateIdCard = queryparams.value.corporateIdCard?.filter(
    (pic: any) => {
      console.log('对比pic:', pic);
      console.log('对比itm:', item);
      return pic !== item.url && pic.url !== item.url
    }
  )
}
onMounted(async () => {
  console.log('baseURL:', baseURL);

  await getmerchant().then(res => {
    if (res.code === 200 && res.data) {
      queryparams.value = res.data
      // if (res.data.businessLicenseList) {
      //   console.log('进来了');
      //   // queryparams.value.businessLicenseList = res.data.businessLicenseList?.map(item => ({ url: baseURL + item.filePath }));
      //   // cpUploadRef1.value.setFileList(queryparams.value.businessLicenseList)
      // } else {
      //   queryparams.value.businessLicenseList = []
      // }

      // if (res.data.corporateIdCard) {
      //   // queryparams.value.corporateIdCard = res.data.corporateIdCard?.map(item => ({ url: baseURL + item.filePath }));
      //   // cpUploadRef2.value.setFileList(queryparams.value.corporateIdCard)
      // } else {
      //   queryparams.value.corporateIdCard = []
      // }
    }
  })
})
</script>
<style lang="scss" scoped>
.info-page {
  // width: 375px;
  width: 100%;
  padding-top: 50px;
  min-height: calc(100vh - 50px);
  // height:100vh;
  background-color: var(--cp-bg);

  .infoImg {
    display: block;
    margin: 20px auto;
  }

  .infoForm {
    margin: 10px auto;
    width: 345px;
    // height: 350px;
    border-radius: 10px;
    overflow: hidden;

    .cp-cell1 {
      margin-top: 10px;
    }

  }
}

.infoForm :deep(.van-field__error-message) {
  position: absolute !important;
  bottom: -18px;
}
</style>